package com.ruoyi.aicall.controller;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.aicall.domain.CcCallPhone;
import com.ruoyi.aicall.domain.CcCallTask;
import com.ruoyi.aicall.domain.CcLlmAgentAccount;
import com.ruoyi.aicall.domain.CcTtsAliyun;
import com.ruoyi.aicall.model.*;
import com.ruoyi.aicall.service.ICcCallPhoneService;
import com.ruoyi.aicall.service.ICcCallTaskService;
import com.ruoyi.aicall.service.ICcLlmAgentAccountService;
import com.ruoyi.aicall.service.ICcTtsAliyunService;
import com.ruoyi.aicall.utils.ClientIpCheck;
import com.ruoyi.cc.domain.CcBizGroup;
import com.ruoyi.cc.domain.CcGateways;
import com.ruoyi.cc.service.ICcBizGroupService;
import com.ruoyi.cc.service.ICcGatewaysService;
import com.ruoyi.cc.service.ICcParamsService;
import com.ruoyi.cc.utils.DateValidatorUtils;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.common.utils.uuid.UuidGenerator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Controller
@Slf4j
@RequestMapping("/aicall/api")
public class ApiController extends BaseController {

    @Autowired
    private ICcCallTaskService callTaskService;
    @Autowired
    private ICcCallPhoneService ccCallPhoneService;
    @Autowired
    private ICcParamsService paramsService;
    @Autowired
    private ICcGatewaysService ccGatewaysService;
    @Autowired
    private ICcLlmAgentAccountService ccLlmAgentAccountService;
    @Autowired
    private ICcBizGroupService ccBizGroupService;
    @Autowired
    private ICcCallTaskService ccCallTaskService;
    @Autowired
    private ICcTtsAliyunService ccTtsAliyunService;

    /**
     * 获取外呼网关列表接口
     * @param req
     * @return
     */
    @GetMapping("/gateway/list")
    @ResponseBody
    public AjaxResult getGatewayList(HttpServletRequest req){
        // 校验客户端ip是否在白名单内
        if (!ClientIpCheck.checkIp(req)) {
            return AjaxResult.error(AjaxResult.Type.NO_AUTH, "未授权，请联系系统管理员添加ip白名单！", "");
        }
        // 获取外呼网关列表
        Map<String, Object> params = new HashMap<>();
        params.put("purposes", Arrays.asList(2,3));
        List<CcGateways> list = ccGatewaysService.selectCcGatewaysList(new CcGateways().setParams(params));
        List<ApiGatewaysModel> result = new ArrayList<>();
        for (CcGateways data: list) {
            ApiGatewaysModel model = new ApiGatewaysModel();
            BeanUtils.copyProperties(data, model);
            result.add(model);
        }
        return AjaxResult.success(result);
    }

    /**
     * 获取大模型列表接口
     * @param req
     * @return
     */
    @GetMapping("/llmacount/list")
    @ResponseBody
    public AjaxResult getLlmAcountList(HttpServletRequest req){
        // 校验客户端ip是否在白名单内
        if (!ClientIpCheck.checkIp(req)) {
            return AjaxResult.error(AjaxResult.Type.NO_AUTH, "未授权，请联系系统管理员添加ip白名单！", "");
        }
        // 获取大模型列表
        List<CcLlmAgentAccount> list = ccLlmAgentAccountService.selectCcLlmAgentAccountList(new CcLlmAgentAccount());
        return AjaxResult.success(list);
    }

    /**
     * 获取音色列表
     * @return
     */
    @GetMapping("/voicecode/list")
    @ResponseBody
    public AjaxResult getVoiceCodeList(HttpServletRequest req)
    {
        // 校验客户端ip是否在白名单内
        if (!ClientIpCheck.checkIp(req)) {
            return AjaxResult.error(AjaxResult.Type.NO_AUTH, "未授权，请联系系统管理员添加ip白名单！", "");
        }
        // 获取音色列表
        List<CcTtsAliyun> list = ccTtsAliyunService.selectCcTtsAliyunList(new CcTtsAliyun());
        JSONArray result = new JSONArray();
        for (CcTtsAliyun ttsAliyun: list) {
            JSONObject obj = new JSONObject();
            obj.put("voiceName", ttsAliyun.getVoiceName());
            obj.put("voiceCode", ttsAliyun.getVoiceCode());
            obj.put("voiceSource", "aliyun_tts");
            result.add(obj);
        }
        return AjaxResult.success(result);
    }


    /**
     * 获取技能组列表
     * @param req
     * @return
     */
    @GetMapping("/busigroup/list")
    @ResponseBody
    public AjaxResult getBusigroupList(HttpServletRequest req){
        // 校验客户端ip是否在白名单内
        if (!ClientIpCheck.checkIp(req)) {
            return AjaxResult.error(AjaxResult.Type.NO_AUTH, "未授权，请联系系统管理员添加ip白名单！", "");
        }
        // 获取技能组列表
        List<CcBizGroup> list = ccBizGroupService.selectCcBizGroupList(new CcBizGroup());
        return AjaxResult.success(list);
    }

    /**
     * 通话记录查询接口（支持按时间、坐席、号码、呼入/呼出类型筛选）
     * @param req
     * @param queryParams
     * @return
     */
    @PostMapping("/calltask/list")
    @ResponseBody
    public TableDataInfo getCallTaskList(HttpServletRequest req, @RequestBody ApiCallTaskQueryParams queryParams)
    {
        TableDataInfo tableDataInfo;
        // 校验请求方ip是否合法
        if (!ClientIpCheck.checkIp(req)) {
            tableDataInfo = new TableDataInfo();
            tableDataInfo.setTotal(0);
            tableDataInfo.setCode(AjaxResult.Type.NO_AUTH.value());
            tableDataInfo.setMsg("未授权，请联系系统管理员添加ip白名单！");
            return tableDataInfo;
        }
        // 处理分页
        if (null == queryParams.getPageNum()) {
            queryParams.setPageNum(1);
        }
        if (null == queryParams.getPageSize()) {
            queryParams.setPageSize(20);
        }
        // 校验参数
        if (StringUtils.isNotEmpty(queryParams.getCreateTimeStart())
                && !DateValidatorUtils.isYmdHms(queryParams.getCreateTimeStart())) {
            tableDataInfo = new TableDataInfo();
            tableDataInfo.setTotal(0);
            tableDataInfo.setCode(AjaxResult.Type.INVALID_PARAM.value());
            tableDataInfo.setMsg("createTimeStart格式不正确，请使用'yyyy-MM-dd HH:mm:ss'格式!");
            return tableDataInfo;
        }
        if (StringUtils.isNotEmpty(queryParams.getCreateTimeEnd())
                && !DateValidatorUtils.isYmdHms(queryParams.getCreateTimeEnd())) {
            tableDataInfo = new TableDataInfo();
            tableDataInfo.setTotal(0);
            tableDataInfo.setCode(AjaxResult.Type.ERROR.value());
            tableDataInfo.setMsg("createTimeEnd格式不正确，请使用'yyyy-MM-dd HH:mm:ss'格式!");
            return tableDataInfo;
        }

        Map<String, Object> params = new HashMap<>();
        params.put("createTimeStart", queryParams.getCreateTimeStart());
        params.put("createTimeEnd", queryParams.getCreateTimeEnd());

        // 分页请求数据
        startPage(queryParams.getPageNum(), queryParams.getPageSize());
        CcCallTask ccCallTask = new CcCallTask();
        ccCallTask.setBatchId(queryParams.getBatchId());
        ccCallTask.setBatchName(queryParams.getBatchName());
        ccCallTask.setParams(params);
        List<CcCallTask> list = ccCallTaskService.selectCcCallTaskList(ccCallTask);
        tableDataInfo = getDataTable(list);
        List<CcCallTask> records = (List<CcCallTask>) tableDataInfo.getRows();
        for (CcCallTask data: records){
            CallTaskStatModel statModel = ccCallPhoneService.statByBatchId(data.getBatchId());
            data.setPhoneCount(statModel.getPhoneCount());
            data.setCallCount(statModel.getCallCount());
            data.setNoCallCount(statModel.getPhoneCount() - statModel.getCallCount());
            data.setConnectCount(statModel.getConnectCount());
            data.setNoConnectCount(statModel.getCallCount() - statModel.getConnectCount());
            if (data.getCallCount() > 0) {
                data.setRealConnectRate(data.getConnectCount()*1.0/data.getCallCount());
            } else {
                data.setRealConnectRate(0.0);
            }
        }
        tableDataInfo.setRows(records);
        return tableDataInfo;
    }

    /**
     * 通话记录查询接口（支持按时间、坐席、号码、呼入/呼出类型筛选）
     * @param req
     * @param queryParams
     * @return
     */
    @PostMapping("/records/list")
    @ResponseBody
    public TableDataInfo getRecordsList(HttpServletRequest req, @RequestBody ApiCallRecordQueryParams queryParams)
    {
        TableDataInfo tableDataInfo;
        // 校验请求方ip是否合法
        if (!ClientIpCheck.checkIp(req)) {
            tableDataInfo = new TableDataInfo();
            tableDataInfo.setTotal(0);
            tableDataInfo.setCode(AjaxResult.Type.NO_AUTH.value());
            tableDataInfo.setMsg("未授权，请联系系统管理员添加ip白名单！");
            return tableDataInfo;
        }
        // 分页参数处理
        if (null == queryParams.getPageNum()) {
            queryParams.setPageNum(1);
        }
        if (null == queryParams.getPageSize()) {
            queryParams.setPageSize(20);
        }
        // 类型（01:呼入， 02:AI外呼， 03:人工外呼）
        String callType = queryParams.getCallType();
        if (StringUtils.isBlank(callType)) {
            tableDataInfo = new TableDataInfo();
            tableDataInfo.setTotal(0);
            tableDataInfo.setCode(AjaxResult.Type.INVALID_PARAM.value());
            tableDataInfo.setMsg("callType不能为空!");
            return tableDataInfo;
        }
        // 校验参数
        if (StringUtils.isNotEmpty(queryParams.getCalloutTimeStart())
                && !DateValidatorUtils.isYmdHms(queryParams.getCalloutTimeStart())) {
            tableDataInfo = new TableDataInfo();
            tableDataInfo.setTotal(0);
            tableDataInfo.setCode(AjaxResult.Type.INVALID_PARAM.value());
            tableDataInfo.setMsg("calloutTimeStart格式不正确，请使用'yyyy-MM-dd HH:mm:ss'格式!");
            return tableDataInfo;
        }
        if (StringUtils.isNotEmpty(queryParams.getCalloutTimeEnd())
                && !DateValidatorUtils.isYmdHms(queryParams.getCalloutTimeEnd())) {
            tableDataInfo = new TableDataInfo();
            tableDataInfo.setTotal(0);
            tableDataInfo.setCode(AjaxResult.Type.INVALID_PARAM.value());
            tableDataInfo.setMsg("calloutTimeStart格式不正确，请使用'yyyy-MM-dd HH:mm:ss'格式!");
            return tableDataInfo;
        }

        if ("01".equals(callType)) {
            // TODO
        } else if ("02".equals(callType)) {
            return getAiCallRecords(queryParams);
        } else if ("03".equals(callType)) {
            // TODO
        } else {
            tableDataInfo = new TableDataInfo();
            tableDataInfo.setTotal(0);
            tableDataInfo.setCode(AjaxResult.Type.INVALID_PARAM.value());
            tableDataInfo.setMsg("callType参数不合法，呼入请输入01，AI外呼请输入02，手工外呼请输入03!");
            return tableDataInfo;
        }
        return null;
    }

    /**
     * 创建外呼任务接口（含任务名称、优先级、并发数、TTS/音频模板等参数）接口
     * @param req
     * @param apiCallTaskModel
     * @return
     */
    @PostMapping("/ai/createTask")
    @ResponseBody
    public AjaxResult createCallTask(HttpServletRequest req, @RequestBody ApiCallTaskModel apiCallTaskModel) {
        // 校验ip白名单
        if (!ClientIpCheck.checkIp(req)) {
            return AjaxResult.error(AjaxResult.Type.NO_AUTH, "未授权，请联系系统管理员添加ip白名单！", "");
        }
        CcCallTask ccCallTask = new CcCallTask();
        // 校验参数
        // 任务名称不能为空
        if (StringUtils.isBlank(apiCallTaskModel.getBatchName())) {
            return AjaxResult.error(AjaxResult.Type.INVALID_PARAM, "batchName不能为空！", "");
        }
        // threadNum不能为空
        if (null == apiCallTaskModel.getThreadNum()) {
            return AjaxResult.error(AjaxResult.Type.INVALID_PARAM, "threadNum不能为空！", "");
        }
        // 校验groupId是否存在
        if (!checkGroupId(apiCallTaskModel.getGroupId())) {
            return AjaxResult.error(AjaxResult.Type.INVALID_PARAM, "groupId参数不合法，请输入正确的groupId！", "");
        }
        // 校验taskType是否合法
        if (null == apiCallTaskModel.getTaskType()) {
            return AjaxResult.error(AjaxResult.Type.INVALID_PARAM, "taskType不能为空！", "");
        } else {
            if (apiCallTaskModel.getTaskType() != 1
                    && apiCallTaskModel.getTaskType() != 2) {
                return AjaxResult.error(AjaxResult.Type.INVALID_PARAM, "taskType参数不合法，AI外呼请输入1，通知提醒请输入2！", "");
            }
        }
        // 校验gatewayId是否合法
        if (!checkGatewayId(apiCallTaskModel.getGatewayId())) {
            return AjaxResult.error(AjaxResult.Type.INVALID_PARAM, "gatewayId参数不合法，请输入正确的gatewayId！", "");
        }
        // AI外呼需要校验llmAccountId是否合法
        if (apiCallTaskModel.getTaskType() == 2) {
            if (!checkLlmAccountId(apiCallTaskModel.getLlmAccountId())) {
                return AjaxResult.error(AjaxResult.Type.INVALID_PARAM, "llmAccountId参数不合法，请输入正确的llmAccountId！", "");
            }
        }
        // playTimes 如果为空，默认值给1
        if (apiCallTaskModel.getTaskType() == 3) {
            if (null == apiCallTaskModel.getPlayTimes()) {
                apiCallTaskModel.setPlayTimes(1);
            }
        }
        // 校验voiceCode、voiceSource是否合法
        if (!checkVoiceCode(apiCallTaskModel.getVoiceCode(), apiCallTaskModel.getVoiceSource())) {
            return AjaxResult.error(AjaxResult.Type.INVALID_PARAM, "voiceCode或voiceSource参数不合法，请输入正确的voiceCode和voiceSource！", "");
        }
        // 创建任务
        BeanUtils.copyProperties(apiCallTaskModel, ccCallTask, "batchId");
        if (null != ccCallTask.getConntectRate() && ccCallTask.getConntectRate() > 0) {
            ccCallTask.setRate(ccCallTask.getConntectRate()/100.0);
        }
        ccCallTask.setCreatetime(System.currentTimeMillis());
        ccCallTaskService.insertCcCallTask(ccCallTask);
        apiCallTaskModel.setBatchId(ccCallTask.getBatchId());
        return AjaxResult.success("success", apiCallTaskModel);
    }

    /**
     * 启动任务接口
     * @param req
     * @param batchId
     * @return
     */
    @GetMapping("/ai/startTask")
    @ResponseBody
    public AjaxResult startTask(HttpServletRequest req, @RequestParam("batchId") Long batchId) {
        // 校验ip白名单
        if (!ClientIpCheck.checkIp(req)) {
            return AjaxResult.error(AjaxResult.Type.NO_AUTH, "未授权，请联系系统管理员添加ip白名单", "");
        }
        // 启动任务
        CcCallTask ccCallTask = ccCallTaskService.selectCcCallTaskByBatchId(batchId);
        if (null == ccCallTask) {
            return AjaxResult.error(AjaxResult.Type.INVALID_PARAM, "参数batchId不合法，请输入正确的batchId", "");
        }
        ccCallTask.setIfcall(1);
        ccCallTask.setExecuting(0L);
        ccCallTask.setStopTime(0L);
        ccCallTaskService.updateCcCallTask(ccCallTask);
        return AjaxResult.success();
    }

    /**
     * 停止任务接口
     * @param req
     * @param batchId
     * @return
     */
    @GetMapping( "/ai/stopTask")
    @ResponseBody
    public AjaxResult stopTask(HttpServletRequest req, @RequestParam("batchId") Long batchId)
    {
        // 校验ip白名单
        if (!ClientIpCheck.checkIp(req)) {
            return AjaxResult.error(AjaxResult.Type.NO_AUTH, "未授权，请联系系统管理员添加ip白名单", "");
        }
        // 停止任务
        CcCallTask ccCallTask = ccCallTaskService.selectCcCallTaskByBatchId(batchId);
        if (null == ccCallTask) {
            return AjaxResult.error(AjaxResult.Type.INVALID_PARAM, "参数batchId不合法，请输入正确的batchId", "");
        }
        ccCallTask.setIfcall(0);
        ccCallTask.setExecuting(0L);
        ccCallTask.setStopTime(System.currentTimeMillis());
        ccCallTaskService.updateCcCallTask(ccCallTask);
        return AjaxResult.success();
    }

    /**
     * 追加名单（不自动启动任务）
     * @param req
     * @param aiCallListModel
     * @return
     */
    @PostMapping("/ai/addCallList")
    @ResponseBody
    public AjaxResult addAiCallList(HttpServletRequest req, @RequestBody AiCallListModel aiCallListModel) {
        if (!ClientIpCheck.checkIp(req)) {
            return AjaxResult.error(AjaxResult.Type.NO_AUTH, "未授权，请联系系统管理员添加ip白名单", "");
        }
        Long batchId = aiCallListModel.getBatchId();
        if (null == batchId) {
            return AjaxResult.error(AjaxResult.Type.INVALID_PARAM, "参数batchId不能为空", "");
        }
        if (CollectionUtils.isEmpty(aiCallListModel.getPhoneList())) {
            return AjaxResult.error(AjaxResult.Type.INVALID_PARAM, "参数phoneList不能为空", "");
        }
        // 获取任务
        CcCallTask ccCallTask = callTaskService.selectCcCallTaskByBatchId(batchId);
        if (null == ccCallTask) {
            return AjaxResult.error(AjaxResult.Type.INVALID_PARAM, "参数batchId不合法，请输入正确的batchId", "");
        }
        if (ccCallTask.getTaskType() != 1) {
            return AjaxResult.error(AjaxResult.Type.INVALID_PARAM, "参数batchId不合法，请输入AI外呼任务（taskType为1）的batchId", "");
        }
        // 追加名单
        Integer successCount = 0;
        List<CcCallPhone> callPhoneList = new ArrayList<>();
        for (String phoneNum: aiCallListModel.getPhoneList()) {
            if (StringUtils.isBlank(phoneNum)) {
                continue;
            }
            JSONObject bizJson = new JSONObject();
            CcCallPhone callPhone = buildCcCallPhone(ccCallTask.getBatchId(), phoneNum, bizJson);
            callPhoneList.add(callPhone);
            successCount ++;
            if (callPhoneList.size() >= 200) {
                ccCallPhoneService.batchInsertCcCallPhone(callPhoneList);
                callPhoneList = new ArrayList<>();
            }
        }
        if (callPhoneList.size() > 0) {
            ccCallPhoneService.batchInsertCcCallPhone(callPhoneList);
        }

        log.info("成功追加" + successCount + "个名单");
        return AjaxResult.success("成功追加" + successCount + "个名单");
    }


    /**
     * 追加外呼名单（不自动启动任务）
     * @param req
     * @param commonCallListModel
     * @return
     */
    @PostMapping("/common/addCallList")
    @ResponseBody
    public AjaxResult addCommonCallList(HttpServletRequest req, @RequestBody CommonCallListModel commonCallListModel) {
        if (!ClientIpCheck.checkIp(req)) {
            return AjaxResult.error(AjaxResult.Type.NO_AUTH, "未授权，请联系系统管理员添加ip白名单", "");
        }
        Long batchId = commonCallListModel.getBatchId();
        if (null == batchId) {
            return AjaxResult.error(AjaxResult.Type.INVALID_PARAM, "参数batchId不能为空", "");
        }
        if (CollectionUtils.isEmpty(commonCallListModel.getPhoneList())) {
            return AjaxResult.error(AjaxResult.Type.INVALID_PARAM, "参数phoneList不能为空", "");
        }
        // 获取任务
        CcCallTask ccCallTask = callTaskService.selectCcCallTaskByBatchId(batchId);
        if (null == ccCallTask) {
            return AjaxResult.error(AjaxResult.Type.INVALID_PARAM, "参数batchId不合法，请输入正确的batchId", "");
        }
        // 通知类的通知内容必填
        if (ccCallTask.getTaskType() == 2) {
            for (CommonPhoneModel commonPhoneModel : commonCallListModel.getPhoneList()) {
                if (StringUtils.isBlank(commonPhoneModel.getNoticeContent())) {
                    return AjaxResult.error(AjaxResult.Type.INVALID_PARAM, "号码" + commonPhoneModel.getPhoneNum() + "的noticeContent不能为空！", "");
                }
            }
        }

        // 追加名单
        Integer successCount = 0;
        List<CcCallPhone> callPhoneList = new ArrayList<>();
        for (CommonPhoneModel commonPhoneModel : commonCallListModel.getPhoneList()) {
            String phoneNum = commonPhoneModel.getPhoneNum();
            if (StringUtils.isBlank(phoneNum)) {
                continue;
            }
            CcCallPhone callPhone = buildCcCallPhone(ccCallTask.getBatchId(), phoneNum, commonPhoneModel.getBizJson());
            callPhone.setTtsText(commonPhoneModel.getNoticeContent());
            callPhoneList.add(callPhone);
            successCount ++;
            if (callPhoneList.size() >= 200) {
                ccCallPhoneService.batchInsertCcCallPhone(callPhoneList);
                callPhoneList = new ArrayList<>();
            }
        }
        if (callPhoneList.size() > 0) {
            ccCallPhoneService.batchInsertCcCallPhone(callPhoneList);
        }
        log.info("成功追加" + successCount + "个名单");
        return AjaxResult.success("成功追加" + successCount + "个名单");
    }


    /**
     * yangqiang定制的追加通知的名单
     * @param req
     * @param noticeCallModel
     * @return
     */
    @PostMapping("/notice/call")
    @ResponseBody
    public AjaxResult callNotice(HttpServletRequest req, @RequestBody NoticeCallModel noticeCallModel) {
        if (!ClientIpCheck.checkIp(req)) {
            return AjaxResult.error(AjaxResult.Type.NO_AUTH, "未授权，请联系系统管理员添加ip白名单", "");
        }
        // 获取任务
        String batchName = paramsService.getParamValueByCode("testNoticeCallTaskName", "test");
        String phoneNum = paramsService.getParamValueByCode("testNoticeCallPhoneNum", "13908113506");
        CcCallTask ccCallTask = callTaskService.selectCcCallTaskByBatchName(batchName, 2);

        // 追加名单
        JSONObject bizJson = new JSONObject();
        CcCallPhone callPhone = buildCcCallPhone(ccCallTask.getBatchId(), phoneNum, bizJson);
        callPhone.setTtsText(noticeCallModel.getNoticeContent());
        ccCallPhoneService.insertCcCallPhone(callPhone);

        // 启动任务
        ccCallTask.setIfcall(1);
        ccCallTask.setExecuting(0L);
        ccCallTask.setStopTime(0L);
        callTaskService.updateCcCallTask(ccCallTask);

        return AjaxResult.success();
    }

    private CcCallPhone buildCcCallPhone(Long batchId, String phoneNum, JSONObject bizJson) {
        CcCallPhone callPhone = new CcCallPhone();
        callPhone.setId(UuidGenerator.GetOneUuid());
        callPhone.setGroupId("1");
        callPhone.setBatchId(batchId);
        callPhone.setCreatetime(new Date().getTime());
        callPhone.setCallstatus(0);
        callPhone.setCalloutTime(0L);
        callPhone.setCallcount(0);
        callPhone.setCallEndTime(0L);
        callPhone.setTimeLen(0L);
        callPhone.setValidTimeLen(0L);
        callPhone.setUuid("");
        callPhone.setConnectedTime(0L);
        callPhone.setHangupCause("");
        callPhone.setAnsweredTime(0L);
        callPhone.setDialogue("");
        callPhone.setWavfile("");
        callPhone.setRecordServerUrl("");
        callPhone.setDialogueCount(0L);
        callPhone.setAcdOpnum("");
        callPhone.setAcdQueueTime(0L);
        callPhone.setAcdWaitTime(0);
        callPhone.setTelephone(phoneNum);
        if (phoneNum.length() > 4) {
            bizJson.put("tailNum", phoneNum.substring(phoneNum.length()-4));
        } else {
            bizJson.put("tailNum", phoneNum);
        }
        callPhone.setCustName(bizJson.getString("custName"));
        return callPhone;
    }


    private TableDataInfo getAiCallRecords(ApiCallRecordQueryParams queryParams) {

        Map<String, Object> params = new HashMap<>();
        params.put("calloutTimeStart", queryParams.getCalloutTimeStart());
        params.put("calloutTimeEnd", queryParams.getCalloutTimeEnd());
        if (null != queryParams.getTimeLenStart()) {
            params.put("timeLenSecondStart", queryParams.getTimeLenStart().toString());
        }
        if (null != queryParams.getTimeLenEnd()) {
            params.put("timeLenSecondEnd", queryParams.getTimeLenEnd().toString());
        }

        startPage(queryParams.getPageNum(), queryParams.getPageSize());
        CcCallPhone ccCallPhone = new CcCallPhone();
        ccCallPhone.setParams(params);
        List<CcCallPhone> list = ccCallPhoneService.selectCcCallPhoneList(ccCallPhone);
        TableDataInfo tableData = getDataTable(list);
        List<CcCallPhone> records = (List<CcCallPhone>) tableData.getRows();
        List<ApiCallRecordQueryResult> apiRecords = new ArrayList<>();
        for (CcCallPhone data: records) {
            ApiCallRecordQueryResult apiData = new ApiCallRecordQueryResult();
            if (data.getWavfile().startsWith("/")) {
                data.setWavfile(data.getWavfile().substring(1));
            }
            data.setWavfile("/recordings/files?filename=" + data.getWavfile());
            apiData.setUuid(data.getUuid());
            apiData.setTelephone(data.getTelephone());
            apiData.setCalloutTime(DateUtils.format(new Date(data.getCalloutTime()), "yyyy-MM-dd HH:mm:ss"));
            if (data.getAnsweredTime() > 0) {
                apiData.setAnsweredTime(DateUtils.format(new Date(data.getAnsweredTime()), "yyyy-MM-dd HH:mm:ss"));
            } else {
                apiData.setAnsweredTime("");
            }
            if (data.getCallEndTime() > 0) {
                apiData.setCallEndTime(DateUtils.format(new Date(data.getCallEndTime()), "yyyy-MM-dd HH:mm:ss"));
            } else {
                apiData.setCallEndTime("");
            }
            apiData.setHangupCause(data.getHangupCause());
            if (data.getTimeLen() > 0) {
                apiData.setWavFileUrl(data.getWavfile());
            } else {
                apiData.setWavFileUrl("");
            }
            if (StringUtils.isNotEmpty(data.getDialogue())) {
                JSONArray dialogue = new JSONArray();
                JSONArray.parseArray(data.getDialogue()).forEach(obj -> {
                    JSONObject json = (JSONObject) obj;
                    if ("assistant".equals(json.getString("role"))
                            || "user".equals(json.getString("role"))) {
                        JSONObject content = new JSONObject();
                        content.put("role", json.getString("role"));
                        content.put("content", json.getString("content"));
                        dialogue.add(content);
                    }
                });
                apiData.setDialogue(dialogue);
            } else {
                apiData.setDialogue(new JSONArray());
            }
            apiData.setTimeLen(Long.valueOf(data.getTimeLen()/1000).intValue());
            apiRecords.add(apiData);
        }
        tableData.setRows(records);
        TableDataInfo tableDataInfo = new TableDataInfo();
        tableDataInfo.setCode(tableData.getCode());
        tableDataInfo.setRows(apiRecords);
        tableDataInfo.setTotal(tableData.getTotal());
        tableDataInfo.setMsg(tableData.getMsg());
        return tableDataInfo;
    }


    private boolean checkGroupId(String groupId) {
        // 可以为空
        if (StringUtils.isBlank(groupId)) {
            return true;
        }
        // 如果传值了，必须是存在的值
        CcBizGroup ccBizGroup = ccBizGroupService.selectCcBizGroupByGroupId(groupId);
        if (null == ccBizGroup) {
            return false;
        }
        return true;
    }

    private boolean checkGatewayId(Long gatewayId) {
        // 不可以为空
        if (null == gatewayId) {
            return false;
        }
        // 必须是存在的网关，且用途是外呼或者不限制
        CcGateways ccGateways = ccGatewaysService.selectCcGatewaysById(gatewayId);
        if (null == ccGateways) {
            return false;
        }
        // 网关用途 0 dropped; 1 phonebar; 2 outbound tasks; 3. Unlimited
        if (ccGateways.getPurpose() != 2
                && ccGateways.getPurpose() != 3) {
            return false;
        }
        return true;
    }

    private boolean checkLlmAccountId(Integer llmAccountId) {
        // 不能为空
        if (null == llmAccountId) {
            return false;
        }
        // 必须存在
        CcLlmAgentAccount ccLlmAgentAccount = ccLlmAgentAccountService.selectCcLlmAgentAccountById(llmAccountId);
        if (null == ccLlmAgentAccount) {
            return false;
        }
        return true;
    }

    private boolean checkVoiceCode(String voiceCode, String voiceSource) {
        // 不能为空
        if (StringUtils.isBlank(voiceCode) || StringUtils.isBlank(voiceSource)) {
            return false;
        }
        // voiceSource仅支持aliyun_tts
        if (!"aliyun_tts".equals(voiceSource)) {
            return false;
        }
        // voiceCode必须是存在的
        CcTtsAliyun ccTtsAliyun = ccTtsAliyunService.selectCcTtsAliyunByVoiceCode(voiceCode);
        if (null == ccTtsAliyun) {
            return false;
        }
        return true;
    }
}
